﻿using MediatR;
using S.Services.SheepMale.Api.Application.Command.MarketCommand;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;

namespace S.Services.SheepMale.Api.Application.CommandHandler.MarketCommandHandler
{
	public class MarketAllReversalCommandHandler : IRequestHandler<MarketAllReversalCommand, int>
	{
		private readonly IRepository<EntityMarket> repository;

		public MarketAllReversalCommandHandler(IRepository<EntityMarket> repository)
		{
			this.repository = repository;
		}

		public async Task<int> Handle(MarketAllReversalCommand request, CancellationToken cancellationToken)
		{
			string[] result = request.marketId.Split(',');
			List<EntityMarket> list = new List<EntityMarket>();
			foreach (var item in result)
			{
				var type = await repository.GetAsync(int.Parse(item));
				if (type.AuditState == 1)
				{
					return -1;
				}
				type.AuditState = 1;
				type.ExamineDate = null;
				type.ExamineBy = null;
				list.Add(type);
			}
            foreach (var item in list)
            {
				return await repository.UpdateAsync(item);
			}
            return 1;
		}
	}
}
